package com.woniu.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniu.dto.OrderDTO;
import com.woniu.entity.Order;
import com.woniu.entity.OrderItem;
import com.woniu.mapper.OrderItemMapper;
import com.woniu.mapper.OrderMapper;
import com.woniu.util.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Configuration
@Slf4j
public class OrderConsumer {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private RedisTemplate redisTemplateInit;

    @RabbitListener(queues = {ConstantUtil.RABBIT_QUEUE_ORDER})
    @Transactional
    public void consume(String msg, Channel channel, Message message) {
        try {
            log.info("消费者收到消息：{}", msg);
            Thread.sleep(2000); // 模拟订单生成时间
            // 业务逻辑
            OrderDTO orderDTO = JSON.parseObject(msg, OrderDTO.class);
            System.out.println(orderDTO);
            Order order = orderDTO.getOrder();
            List<OrderItem> orderItems = orderDTO.getOrderDetailList();
            Object o = redisTemplateInit.opsForValue().get(ConstantUtil.REDIS_ORDER + order.getOrderId());
            if (o != null) {
                // 插入主订单
                Integer insertOrderResult = orderMapper.add(order);
                if (insertOrderResult <= 0) {
                    throw new RuntimeException("添加订单主表失败");
                }
                // 批量插入订单子项
                if (!orderItems.isEmpty()) {
                    int batchResult = orderItemMapper.batchInsertOrderItems(orderItems);
                    if (batchResult <= 0) {
                        throw new RuntimeException("批量插入订单项失败");
                    }
                }
            // 删除唯一标识
            redisTemplateInit.delete(ConstantUtil.REDIS_ORDER + order.getOrderId());
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
